﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using MySql.Data.MySqlClient;
using CodeRobot.Utility;
using System.Windows.Forms;

namespace CodeRobot.DAL
{
    /// <summary>
    /// .net core处理请求类
    /// </summary>
    public class ViewCreateHelper
    {

        /// <summary>
        /// 根据表名创建Create新增页面
        /// </summary>
        /// <param name="strFilePath">保存路径</param>
        /// <param name="strProjectName">项目名</param>
        /// <param name="strTableName">表名</param>
        public static void CreateViewCreateClass(string strFilePath,string strProjectName, string strTableName,string strTableComment, string strDBName)
        {
            //读取版权信息
            CodeRobot.Utility.IniFile iniFile = new Utility.IniFile(Application.StartupPath + "\\config.ini");
            string strCompany = iniFile.GetString("COPYRIGHT", "COMPANY", "");
            string strAuthor = iniFile.GetString("COPYRIGHT", "AUTHOR", "");
            string strVersion = iniFile.GetString("COPYRIGHT", "VERSION", "");
            string strCode = iniFile.GetString("COPYRIGHT", "CODE", "");
            string strCreateDate = iniFile.GetString("BASE", "CREATE_DATE", "");
            string strTablePrefix = iniFile.GetString("BASE", "TABLE_PREFIX", "");

            string strTableNameUpper = CommonHelper.GetTableNameUpper(strTableName);
            
            string strPrimaryKey = CommonHelper.GetPrimaryKey(strTableName);//如：news_id

            string strAllColumnName = CommonHelper.GetAllColumnName(strTableName);
            string strAllColumnNameNotKey = CommonHelper.GetAllColumnNameNotKey(strTableName);

            string strClassName = CommonHelper.GetClassName(strTableName);//类名
            strClassName = CommonHelper.GetTableNameUpper(strClassName);
            string strTableNameSpec = CommonHelper.GetTableNameFirstLowerSecondUpper(strClassName);//如：newsTypes
            string strTableNameLower = strTableNameSpec.ToLower();//如：newstypes

            Directory.CreateDirectory(strFilePath);
            //为每个表创建一个独立目录存放
            string strTableNamePath = strFilePath + "\\"+ strClassName;
            if (!Directory.Exists(strTableNamePath))
            {
                Directory.CreateDirectory(strTableNamePath);
            }
            StreamWriter sw = new StreamWriter(strTableNamePath + "\\Create.cshtml", false, Encoding.GetEncoding("utf-8"));//生成物理文件
            string strTableComment2 = CommonHelper.GetColumnKeyComment(strTableComment);

            sw.WriteLine("@{");
            sw.WriteLine("    ViewData[\"Title\"] = \"新增" + strTableComment2 + "\";");
            sw.WriteLine("    Layout = \"~/Views/Shared/_LayoutNone.cshtml\";");
            sw.WriteLine("}");
            sw.WriteLine("<div class=\"layui-form\" lay-filter=\"layuiadmin-app-form-list\" id=\"layuiadmin-app-form-list\" style=\"padding: 20px 30px 0 0;\">");
            sw.WriteLine(GetCreateItemList(strDBName, strTableName));
            sw.WriteLine("    <div class=\"layui-form-item layui-hide\">");
            sw.WriteLine(CommonHelper.GetUploadImgHiddenInput(strDBName, strTableName));
            sw.WriteLine("        <input type=\"hidden\" id=\"parent_id\" name=\"parent_id\" value=\"@ViewContext.HttpContext.Request.Query[\"parent_id\"]\">");
            sw.WriteLine("        <input type=\"button\" lay-submit lay-filter=\"layuiadmin-app-form-submit\" id=\"layuiadmin-app-form-submit\" value=\"确认添加\">");
            sw.WriteLine("        <input type=\"button\" lay-submit lay-filter=\"layuiadmin-app-form-edit\" id=\"layuiadmin-app-form-edit\" value=\"确认编辑\">");
            sw.WriteLine("    </div>");
            sw.WriteLine("");
            sw.WriteLine("</div>");
            sw.WriteLine("");
            sw.WriteLine("<script src=\"~/layuiadmin/layui/layui.js\"></script>");
            sw.WriteLine("<script>");
            sw.WriteLine("    layui.config({");
            sw.WriteLine("        base: '/layuiadmin/' // 静态资源所在路径");
            sw.WriteLine("    }).extend({");
            sw.WriteLine("        index: '/lib/index' // 主入口模块");
            sw.WriteLine("    }).use(['index', 'laydate', 'form', 'upload', 'laydate'], function () {");
            sw.WriteLine("        var $ = layui.$");
            sw.WriteLine("            , form = layui.form");
            sw.WriteLine("            , admin = layui.admin");
            sw.WriteLine("            , upload = layui.upload");
            sw.WriteLine("            , layedit = layui.layedit");
            sw.WriteLine("            , laydate = layui.laydate;");
            sw.WriteLine("");
            //sw.WriteLine("        laydate.render({");
            //sw.WriteLine("            elem: '#此处字段需要根据实际业务逻辑修改'");
            //sw.WriteLine("        });");
            
            if (CommonHelper.GetSelectScript(strProjectName, strDBName, strTableName, strTablePrefix).Contains("admin.req") || CommonHelper.GetSelectArea(strProjectName, strDBName, strTableName).Contains("admin.req"))
            {
                sw.WriteLine("        // 默认加载");
                sw.WriteLine("        $(function () {");
                // sw.WriteLine("            // 读取数据加载loading..");
                sw.WriteLine("            loading = layer.load(2, {");
                sw.WriteLine("                shade: [0.2, '#000']");
                sw.WriteLine("            });");
                sw.WriteLine(CommonHelper.GetSelectScript(strProjectName, strDBName, strTableName, strTablePrefix));
                sw.WriteLine("        });");
            }
            sw.WriteLine("");
            sw.WriteLine(CommonHelper.GetSwitchScript(strDBName, strTableName));
            sw.WriteLine("");
            sw.WriteLine(CommonHelper.GetUploadImgScript(strProjectName, strDBName, strTableName));
            sw.WriteLine("");
            sw.WriteLine("        // 监听提交");
            sw.WriteLine("        form.on('submit(layuiadmin-app-form-submit)', function (data) {");
            sw.WriteLine("            var field = data.field; // 获取提交的字段");
            sw.WriteLine("            var index = parent.layer.getFrameIndex(window.name); // 先得到当前iframe层的索引");
            sw.WriteLine("");
            sw.WriteLine("            // 提交 Ajax 成功后，关闭当前弹层并重载表格");
            sw.WriteLine("            loading = layer.load(2, {");
            sw.WriteLine("                shade: [0.2, '#000']");
            sw.WriteLine("            });");
            sw.WriteLine("");
            sw.WriteLine("            // 提交数据");
            sw.WriteLine("            admin.req({");
            sw.WriteLine("                headers: {");
            sw.WriteLine("                    'RequestVerificationToken': csrfToken");
            sw.WriteLine("                },");
            sw.WriteLine("                method: 'POST',");
            sw.WriteLine("                url: '/"+ strTableNameLower + "/create'");
            sw.WriteLine("                , data: data.field");
            sw.WriteLine("                , done: function (res) {");
            sw.WriteLine("                    // console.log(`res=${JSON.stringify(res)}`)");
            sw.WriteLine("                    layer.close(loading);");
            sw.WriteLine("                    parent.layui.table.reload('LAY-app-content-list'); // 重载表格");
            sw.WriteLine("                    if(res.errcode){");
            sw.WriteLine("                        layer.open({");
            sw.WriteLine("                          title: '错误提示'");
            sw.WriteLine("                          ,type: 1");
            sw.WriteLine("                           ,content: '<div style=\"color: red; padding: 20px; \">'+ res.errcode +':'+ res.errmsg +'</div>'");
            sw.WriteLine("                          ,btn: [\"确定\"]");
            sw.WriteLine("                        });");
            sw.WriteLine("                    } else {");
            sw.WriteLine("                        parent.layer.close(index);");
            sw.WriteLine("                    }");
            sw.WriteLine("                }");
            sw.WriteLine("            });");
            sw.WriteLine("        });");
            sw.WriteLine("    })");
            sw.WriteLine("</script>");

            sw.Close();
        }

        /// <summary>
        /// 获取新增字段列表(区别于MutiPages页面)
        /// </summary>
        /// <param name="strTableName"></param>
        /// <returns></returns>
        public static string GetCreateItemList(string strDBName, string strTableName)
        {
            string strReturnValue = "";

            try
            {
                int num = 0;
                MySqlConnection cn = new MySqlConnection(CodeRobot.DBSqlHelper.DBMySQLHelper.ConnectionMySQL());
                cn.Open();
                string strSql = "SELECT COLUMN_NAME,DATA_TYPE,COLUMN_TYPE,COLUMN_KEY,COLUMN_COMMENT,EXTRA,COLUMN_DEFAULT,CHARACTER_SET_NAME,CHARACTER_MAXIMUM_LENGTH FROM `information_schema`.`COLUMNS` WHERE TABLE_SCHEMA='" + strDBName + "' AND TABLE_NAME='" + strTableName + "' ORDER BY ordinal_position ";
                MySqlCommand cmd = new MySqlCommand(strSql, cn);
                MySqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    string strColumnName = dr["COLUMN_NAME"].ToString();//字段列名
                    string strColumnKey = dr["COLUMN_KEY"].ToString();//是否是主键
                    string strColumnComment = dr["COLUMN_COMMENT"].ToString();//注释
                    string strMaxLength = dr["CHARACTER_MAXIMUM_LENGTH"].ToString();//字段长度

                    if (strColumnKey == "PRI" || strColumnName == "created_at")
                    {
                        //
                    }
                    else
                    {
                        if (strColumnComment.Contains("{勾选}"))
                        {
                            string strColumnComment2 = CommonHelper.GetColumnKeyComment(strColumnComment);
                            string strColumnComment3 = CommonHelper.GetColumnKeyCommentRight(strColumnComment);

                            string strValue = "    <div class=\"layui-form-item\">\r\n";
                            strValue += "        <label class=\"layui-form-label\">" + strColumnComment2 + "</label>\r\n";
                            strValue += "        <div class=\"layui-input-block\">\r\n";
                            strValue += "            <input type=\"checkbox\" lay-verify=\"required\" lay-filter=\"switch_" + strColumnName + "\" id=\"switch_" + strColumnName + "\" name=\"switch_" + strColumnName + "\"  lay-skin=\"switch\" lay-text=\"" + strColumnComment3 + "\" checked>\r\n";
                            strValue += "            <input type=\"hidden\" name=\"" + strColumnName + "\" id=\"" + strColumnName + "\" value=\"true\" />\r\n";
                            strValue += "        </div>\r\n";
                            strValue += "    </div>\r\n";
                            strValue += "    \r\n";

                            strReturnValue += strValue;
                        }
                        else if (strColumnComment.Contains("{下拉}"))
                        {
                            string strColumnComment2 = CommonHelper.GetColumnKeyComment(strColumnComment);

                            string strValue = "    <div class=\"layui-form-item\">\r\n";
                            strValue += "        <label class=\"layui-form-label\">" + strColumnComment2 + "</label>\r\n";
                            strValue += "        <div class=\"layui-input-block\">\r\n";
                            strValue += "                <select id=\"" + strColumnName + "\" name=\"" + strColumnName + "\" lay-verify=\"required\">\r\n";
                            strValue += "                    <option value=\"\">选择" + strColumnComment2 + "</option>\r\n";
                            strValue += "                </select>\r\n";
                            strValue += "        </div>\r\n";
                            strValue += "    </div>\r\n";
                            strValue += "    \r\n";

                            strReturnValue += strValue;
                        }
                        else if (strColumnComment.Contains("{图片}"))
                        {
                            string strColumnComment2 = CommonHelper.GetColumnKeyComment(strColumnComment);

                            string strValue = "                        <div class=\"layui-form-item\">\r\n";
                            strValue += "                            <label class=\"layui-form-label\">" + strColumnComment2 + "</label>\r\n";
                            strValue += "                            <div class=\"layui-input-block\">\r\n";
                            strValue += "                                    <div class=\"layui-upload-drag\" id=\"cover-upload-drag\">\r\n";
                            strValue += "                                        <i class=\"layui-icon\"></i>\r\n";
                            strValue += "                                        <p>点击上传，或将图片拖拽到此处</p>\r\n";
                            strValue += "                                        <label style=\"color:#dc2828\">*图片比例建议:16*9</label>\r\n";
                            strValue += "                                    </div>\r\n";
                            strValue += "                            </div>\r\n";
                            strValue += "                        </div>\r\n";
                            strReturnValue += strValue;
                        }
                        else
                        {
                            string strColumnComment2 = CommonHelper.GetColumnKeyComment(strColumnComment);

   
                            string strValue = "    <div class=\"layui-form-item\">\r\n";
                            if (num == 0)
                            {
                                strValue += "        <label class=\"layui-form-label\"><span style=\"color:red\">*</span> " + strColumnComment2 + "</label>\r\n";
                            }
                            else
                            {
                                strValue += "        <label class=\"layui-form-label\">" + strColumnComment2 + "</label>\r\n";  
                            }   
                            strValue += "        <div class=\"layui-input-block\">\r\n";    
                            if (strColumnName.Contains("remark") || strColumnName.Contains("summary") || strColumnName.Contains("content") || strColumnName.Contains("content") || strColumnName.Contains("content") || strColumnName.Contains("intro") || strColumnComment.Contains("{TEXTAREA}"))
                            {
                                strValue += "            <textarea id=\"" + strColumnName + "\" name=\"" + strColumnName + "\" lay-verify=\"required\" placeholder=\"请输入" + strColumnComment2 + "\" autocomplete=\"off\" class=\"layui-textarea\"></textarea>\r\n";
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(strMaxLength))
                                {
                                    strValue += "            <input type=\"text\" id=\"" + strColumnName + "\" name=\"" + strColumnName + "\" maxlength=\"" + strMaxLength + "\" lay-verify=\"required\" placeholder=\"请输入" + strColumnComment2 + "\" autocomplete=\"off\" class=\"layui-input\">\r\n";
                                }
                                else
                                {
                                    strValue += "            <input type=\"text\" id=\"" + strColumnName + "\" name=\"" + strColumnName + "\" lay-verify=\"required\" placeholder=\"请输入" + strColumnComment2 + "\" autocomplete=\"off\" class=\"layui-input\">\r\n";
                                }
                            }
                            strValue += "        </div>\r\n";
                            strValue += "    </div>\r\n";

                            strReturnValue += strValue;
                        }
                    }
                }
                dr.Dispose();
                cn.Close();
            }
            catch (Exception ex)
            {
                CodeRobot.Utility.LogHelper.Error(typeof(CodeHelper), ex, "获取新增字段列表", "GetCreateItemList", false);
            }

            return strReturnValue;

        }

    }
}
